<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\store\controller;

use library\Controller;
use library\tools\Data;
use think\Db;
use app\store\model\Common;
use think\facade\Config;

/**
 * 商品信息管理
 * Class Goods
 * @package app\store\controller
 */
class Goods extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'StoreGoods';
    protected $table1 = 'store_goods';

    /**
     * 商品信息管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $where = "";
        if(!empty($_GET['cate_id'])){
            $cate_id = $_GET['cate_id'];
            $where = "cate_id=$cate_id";
        }else{
            if(!empty($_GET['cate_id_two'])){
                $cate_id = $_GET['cate_id_two'];
                $where = "cate_id=$cate_id";
            }else{
                if(!empty($_GET['cate_id_one'])){
                    $cate_id = $_GET['cate_id_one'];
                    $where = "cate_id=$cate_id";
                }
            }
        }

        $this->title = '商品信息管理';
        $query = $this->_query($this->table)->equal('status,shop_id,text_id,tag_id')->like('title');
        $query->where($where)->where(['is_deleted' => '0'])->where(['is_shenhe' => '1'])->order('sort desc,id desc')->page();
    }


    public function shua(){
        $list = Db::query("select id,logo,image,content from $this->table1");
        $common = new Common();
        $common->shua($list,$this->table1,3);
        $url = url('@admin') . '#' . url('@store/goods/index') . '?spm=' . $this->request->get('spm');
        $this->success('刷新成功！', $url);
    }
    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(&$data)
    {
        $this->clist_two = $this->clist_three = [];
        if(!empty($_GET['cate_id_one'])){
            $cate_id_one = $_GET['cate_id_one'];
            $where = "pid=$cate_id_one";
            $this->clist_two = Db::name('StoreGoodsCate')->where(['is_deleted' => '0', 'status' => '1'])->where($where)->select();
        }

        if(!empty($_GET['cate_id_two'])){
            $cate_id_two = $_GET['cate_id_two'];
            $where = "pid=$cate_id_two";
            $this->clist_three = Db::name('StoreGoodsCate')->where(['is_deleted' => '0', 'status' => '1'])->where($where)->select();
        }


        $this->clist = Db::name('StoreGoodsCate')->where(['is_deleted' => '0', 'status' => '1'])->select();
        $this->clist_one = Db::name('StoreGoodsCate')->where(['is_deleted' => '0', 'status' => '1', 'pid' => '0'])->select();

        $this->shop_list = array(array("id"=>1,'title'=>'平台'));
        $this->text_list = Db::name('SystemText')->where(['is_deleted' => '0', 'status' => '1'])->select();
        $this->tag_list = Db::table("system_banner")->where(['is_deleted' => '0','cate_id'=>2, 'status' => '1'])->select();

        $this->clist = $this->arr2table($this->clist);
        foreach ($this->clist as $key => &$cate) {
            if (isset($vo['pid'])) {
                $path = "-{$vo['pid']}-{$vo['id']}";
                if ($vo['pid'] !== '' && (stripos("{$cate['path']}-", "{$path}-") !== false || $cate['path'] === $path)) {
                    unset($this->clist[$key]);
                }
            }
        }
        $shop_list = $this->shop_list ;
        $cate_list = $this->clist ;
        $list = Db::name('StoreGoodsList')->where('status', '1')->whereIn('goods_id', array_unique(array_column($data, 'id')))->select();
        foreach ($data as &$vo) {
            list($vo['list'], $vo['cate']) = [[], []];
            foreach ($list as $goods) if ($goods['goods_id'] === $vo['id']) array_push($vo['list'], $goods);
            foreach ($cate_list as $v) if ($v['id'] === $vo['cate_id']) $vo['cate'] = $v;
            foreach ($shop_list as $vv) if ($vv['id'] === $vo['shop_id']) $vo['shop'] = $vv;
            $tag_id = $vo['tag_id'];
            $vo['tag_name'] = Db::name("SystemBanner")->where("id=$tag_id")->value('title');
            $text_id = $vo['text_id'];
            $vo['text_name'] = Db::name("SystemText")->where("id=$text_id")->value('title');

            $cate_id = $vo['cate_id'];
            $level = Db::name("StoreGoodsCate")->where("id=$cate_id")->where("pid=0")->value("id");
            if($level){
                $vo['level_name'] = '<span style="color: red">一级</span>';
            }else{
                $pid = Db::name("StoreGoodsCate")->where("id=$cate_id")->value("pid");
                $level2 = Db::name("StoreGoodsCate")->where("id=$pid")->value("pid");
                if($level2==0){
                    $vo['level_name'] = '<span style="color: orange">二级</span>';
                }else{
                    $vo['level_name'] = '<span style="color: green">三级</span>';
                }
            }
        }
    }

    //商品一级分类
    public function cate_id_one(){
        $cate_id_one  = $_POST['cate_id_one'];
        $list = Db::query("select * from store_goods_cate where pid=$cate_id_one and is_deleted=0 and status=1");
        echo json_encode($list);
    }

    //商品二级分类
    public function cate_id_two(){
        $cate_id_two  = $_POST['cate_id_two'];
        $list = Db::query("select * from store_goods_cate where pid=$cate_id_two and is_deleted=0 and status=1");
        echo json_encode($list);
    }


    /**
     * 商品库存入库
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function stock()
    {
        if ($this->request->isGet()) {
            $GoodsId = $this->request->get('id');
            $goods = Db::name('StoreGoods')->where(['id' => $GoodsId])->find();
            empty($goods) && $this->error('无效的商品信息，请稍候再试！');
            $goods['list'] = Db::name('StoreGoodsList')->where(['goods_id' => $GoodsId])->select();
            $this->fetch('', ['vo' => $goods]);
        } else {
            list($post, $data) = [$this->request->post(), []];
            if (isset($post['id']) && isset($post['goods_id']) && is_array($post['goods_id'])) {
                foreach (array_keys($post['goods_id']) as $key) if ($post['goods_number'][$key] > 0) array_push($data, [
                    'goods_id'     => $post['goods_id'][$key],
                    'goods_spec'   => $post['goods_spec'][$key],
                    'number_stock' => $post['goods_number'][$key],
                ]);
                if (!empty($data)) {
                    Db::name('StoreGoodsStock')->insertAll($data);
                    \app\store\service\GoodsService::syncStock($post['id']);
                    $this->success('商品信息入库成功！');
                }
            }
            $this->error('没有需要商品入库的数据！');
        }
    }

    /**
     * 添加商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->title = '添加商品信息';
        $this->isAddMode = '1';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->title = '编辑商品信息';
        $this->isAddMode = '0';
        $this->_form($this->table, 'form');
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    protected function _form_filter(&$data)
    {
        // 生成商品ID
        if (empty($data['id'])) $data['id'] = Data::uniqidNumberCode(14);
        if ($this->request->isGet()) {
            $fields = 'goods_spec,goods_id,status,price_market market,price_selling selling,number_virtual `virtual`,number_express express,daohuo,fahuo,is_sku,price_integral,price_arrears';
            $defaultValues = Db::name('StoreGoodsList')->where(['goods_id' => $data['id']])->column($fields);
            $this->defaultValues = json_encode($defaultValues, JSON_UNESCAPED_UNICODE);
            $this->cates = Db::name('StoreGoodsCate')->where(['is_deleted' => '0', 'status' => '1','pid'=>0])->order('sort desc,id desc')->select();

            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->catess = (array)Db::name('StoreGoodsCate')->where($where)->order('sort desc,id desc')->select();
            $this->catess = $this->arr2table($this->catess);
            foreach ($this->catess as $key => &$cate) {
                if (isset($vo['pid'])) {
                    $path = "-{$vo['pid']}-{$vo['id']}";
                    if ($vo['pid'] !== '' && (stripos("{$cate['path']}-", "{$path}-") !== false || $cate['path'] === $path)) {
                        unset($this->catess[$key]);
                    }
                }
            }
            $this->tuijian_list = Db::table("system_tuijian")->where(['is_deleted' => '0', 'status' => '1'])->select();;
            $this->text_list = Db::table("system_text")->where(['is_deleted' => '0', 'status' => '1'])->select();
            $this->tag_list = Db::table("system_banner")->where(['is_deleted' => '0','cate_id'=>2, 'status' => '1'])->select();

            $this->shop_list = array(array("id"=>1,'title'=>'平台'));


        } elseif ($this->request->isPost()) {
            $data['is_shenhe'] = 1;
//            if (empty($data['logo'])) $this->error('商品LOGO不能为空，请上传图片');
            if (empty($data['image'])) $this->error('商品展示图片不能为空，请上传图片');

            $data['logo'] = explode('|',$data['image'])[0];

            Db::name('StoreGoodsList')->where(['goods_id' => $data['id']])->update(['status' => '0']);
            foreach (json_decode($data['lists'], true) as $vo) Data::save('StoreGoodsList', [
                'goods_id'       => $data['id'],
                'goods_spec'     => $vo[0]['key'],
                'price_market'   => $vo[0]['market'],
                'price_selling'  => $vo[0]['selling'],
                'number_virtual' => $vo[0]['virtual'],
                'daohuo'            => $vo[0]['daohuo'],
                'fahuo'             => $vo[0]['fahuo'],
                'is_sku'            => $vo[0]['is_sku'],
                'price_integral'    => $vo[0]['price_integral'],
                'price_arrears'     => $vo[0]['price_arrears'],
                'number_express' => $vo[0]['express'],
                'status'         => $vo[0]['status'] ? 1 : 0,
            ], 'goods_spec', ['goods_id' => $data['id']]);

        }
    }


    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result($result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('商品编辑成功！', 'javascript:history.back()');
        }
    }

    /**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id ID Key
     * @param string $pid 父ID Key
     * @param string $path
     * @param string $ppath
     * @return array
     */
    private  function arr2table(array $list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
    {
        $tree = [];
        foreach ($this->arr2tree($list, $id, $pid) as $attr) {
            $attr[$path] = "{$ppath}-{$attr[$id]}";
            $attr['sub'] = isset($attr['sub']) ? $attr['sub'] : [];
            $attr['spt'] = substr_count($ppath, '-');
            $str = "    "."    ". '├' . "    ";
            $attr['spl'] = str_repeat("$str", $attr['spt']);
            $sub = $attr['sub'];
            unset($attr['sub']);
            $tree[] = $attr;
            if (!empty($sub)) $tree = array_merge($tree, self::arr2table($sub, $id, $pid, $path, $attr[$path]));
        }
        return $tree;
    }


    /**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return array
     */
    private  function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) $map[$item[$id]] = $item;
        foreach ($list as $item) if (isset($item[$pid]) && isset($map[$item[$pid]])) {
            $map[$item[$pid]][$son][] = &$map[$item[$id]];
        } else $tree[] = &$map[$item[$id]];
        unset($map);
        return $tree;
    }

    /**
     * 禁用商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除商品信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

}
